﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using SIMSProject.ControlTemplates.SIMSProject;
using Microsoft.SharePoint.WebControls;
using System.Data;
using SIMSProject.Common;
namespace SIMSProject.Views.Inventory.ProductTracking
{
    public partial class ProductTrackingUserControl : UserControl
    {
        SPItem item = SPContext.Current.Item;
        SPWeb web = SPContext.Current.Web;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SPContext.Current.FormContext.FormMode != SPControlMode.New)
            {
                this.ffTrackingType.ControlMode = SPControlMode.Display;
            }
            if (!IsPostBack)
            {
                this.hdfSessionName.Value = Guid.NewGuid().ToString().Replace("-", "");
                this.btReject.Attributes.Add("onclick", "if($('#tdDirectorComment textarea').val()==''){alert('Please enter comment!');return false;};return confirm('Are you sure to reject this request ?')");
            }
            ShowHideControl();
        }

        protected void ShowHideControl()
        {
            if (item["Status"] == null || item["Status"].ToString() == "")
            {
                this.trApproveDate.Visible = false;
                this.trDirector.Visible = false;
                this.trDirectorComment.Visible = false;
                if (SPContext.Current.FormContext.FormMode != SPControlMode.Display) 
                {
                    this.btSave.Visible = true;
                }
            }
            else
            {
                this.trApproveDate.Visible = true;
                this.trDirector.Visible = true;
                this.trDirectorComment.Visible = true;
                this.Title.ControlMode = SPControlMode.Display;
                this.ffDescription.ControlMode = SPControlMode.Display;
                if (item["Status"].ToString() == "Director Review" && web.IsCurrentUserMemberOfGroup(web.Groups[Constant.Groups.Director].ID) && SPContext.Current.FormContext.FormMode != SPControlMode.Display)
                {
                    this.btApprove.Visible = true;
                    this.btReject.Visible = true;
                    this.ffDirectorComment.ControlMode = SPControlMode.Edit;
                }
                else
                {
                    this.ffDirectorComment.ControlMode = SPControlMode.Display;
                }
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            ProductAdding productAddingControl = (ProductAdding)Page.LoadControl("~/_CONTROLTEMPLATES/SIMSProject/ProductAdding.ascx");
            productAddingControl.ParentListName = "Product Tracking";
            productAddingControl.SetSessionName (this.hdfSessionName.Value);
            productAddingControl.parentPage = this;
            this.phProductAddingModule.Controls.Add(productAddingControl);
        }

        public string GetTrackingType()
        {
            return this.ffTrackingType.Value.ToString();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit || SPContext.Current.FormContext.FormMode == SPControlMode.New)
            {
                SPContext.Current.FormContext.OnSaveHandler += this.CustomSaveHandler;
            }
        }

        private void CustomSaveHandler(object o, EventArgs e)
        {

            UpdateProduct();
            SPContext.Current.Item["Year"] = DateTime.Now.Year;
            SPContext.Current.Item["Month"] = DateTime.Now.Month;
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            SaveButton.SaveItem(SPContext.Current, false, string.Empty);
        }

        private void UpdateProduct()
        {
            DataTable dt = Session[this.hdfSessionName.Value] as DataTable;
            int id, quantity;

            SPSite siteColl = SPContext.Current.Site;
            SPWeb site = SPContext.Current.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
                {
                    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))
                    {

                        SPList listProduct = ElevatedSite.Lists["Product"];
                        SPListItem item;
                        if (dt != null)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                id = (int)dr["id"];
                                quantity = (int)dr["Quantity"];
                                item = listProduct.GetItemById(id);
                                int currentQuantity = Convert.ToInt32(item["Quantity"]);
                                if (this.ffTrackingType.Value.ToString() == "Import")
                                {
                                    item["Quantity"] = currentQuantity + quantity;
                                }
                                else if (this.ffTrackingType.Value.ToString() == "Export" || this.ffTrackingType.Value.ToString() == "Remove")
                                {
                                    item["Quantity"] = currentQuantity - quantity;
                                }
                                ElevatedSite.AllowUnsafeUpdates = true;
                                item.Update();
                                ElevatedSite.AllowUnsafeUpdates = false;
                            }
                        }
                    }
                }
            });
        }

        private void UpdateProductDetail()
        {
            int id = SPContext.Current.Item.ID;
            int totalQuantity = 0;
            DataTable productTable = (DataTable)Session[this.hdfSessionName.Value];

            SPList childList = SPContext.Current.Web.Lists["Product Tracking Detail"];

            for (int i = 0; i < productTable.Rows.Count; i++)
            {
                SPQuery query = new SPQuery();
                query.Query = "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + id.ToString() + "</Value></Eq><Eq><FieldRef Name='Product_x0020_Id' /><Value Type='Text'>" + Convert.ToString(productTable.Rows[i]["id"]) + "</Value></Eq></And></Where>";
                if (childList.GetItems(query).Count == 0)
                {
                    SPListItem item = childList.Items.Add();
                    item["Title"] = id;
                    item["Product Name"] = productTable.Rows[i]["ProductName"];
                    item["Product Code"] = productTable.Rows[i]["ProductCode"];
                    item["Product Id"] = productTable.Rows[i]["id"];
                    item["Quantity"] = productTable.Rows[i]["Quantity"];
                    item.Update();
                }
                else
                {
                    SPListItem item = childList.GetItems(query)[0];
                    item["Quantity"] = productTable.Rows[i]["Quantity"];
                    item.Update();
                }

                int temp = 0;
                Int32.TryParse(Convert.ToString(productTable.Rows[i]["Quantity"]), out temp);
                totalQuantity += temp;
            }

            SPContext.Current.Item["Total Quantity"] = totalQuantity;
            SaveButton.SaveItem(SPContext.Current, false, string.Empty);
        }

        private bool CheckProduct()
        {
            DataTable dt = Session[this.hdfSessionName.Value] as DataTable;
            if (dt != null && dt.Rows.Count != 0)
            {
                string message = string.Empty;

                foreach (DataRow dr in dt.Rows)
                {
                    int id = 0;
                    Int32.TryParse(Convert.ToString(dr["id"]), out id);
                    int quantity = 0;
                    Int32.TryParse(Convert.ToString(dr["Quantity"]), out quantity);

                    SPListItem product = SPContext.Current.Web.Lists["Product"].GetItemById(id);

                    int productQuantity = 0;
                    Int32.TryParse(Convert.ToString(product["Quantity"]), out productQuantity);

                    if (quantity > productQuantity)
                    {
                        message += "The quanlity of " + product["Title"] + " is not enough\\r\\n";

                    }
                }
                if (message != string.Empty)
                {
                    message = "<script type='text/javascript'>window.alert('" + message + "');</script>";
                    this.Page.Response.Write(message);
                    return false;
                }
                else return true;
            }
            else
            {
                this.Page.Response.Write("<script type='text/javascript'>window.alert('Please insert some Product to this tracking');</script>");
                return false;
            }
        }

        protected void btSave_Click(object o, EventArgs e)
        {
            if (Page.IsValid)
            {
                if (this.ffTrackingType.Value.ToString() == "Export" || this.ffTrackingType.Value.ToString() == "Remove")
                {
                    if (!CheckProduct()) return;
                }
                else
                {

                    DataTable dt = Session[this.hdfSessionName.Value] as DataTable;
                    if (dt == null || dt.Rows.Count == 0)
                    {
                        this.Page.Response.Write("<script type='text/javascript'>window.alert('Please insert some Material to this tracking');</script>");
                        return;
                    }
                }

                if (SPContext.Current.FormContext.FormMode == SPControlMode.New)
                {
                    SPContext.Current.Web.AllowUnsafeUpdates = true;
                    SaveButton.SaveItem(SPContext.Current, false, string.Empty);
                    if (this.ffTrackingType.Value.ToString() != "Remove")
                    {
                        UpdateProduct();
                    }
                    else
                    {
                        item["Status"] = "Director Review";
                        Common.Common.SendEmail(web, Common.Common.GetEmailAddressesFromName("Director"), string.Empty, "[SIMS][Remove Invalid Material Request]&nbsp;" + item["Title"], this.BuildMailContent());
                    }
                    UpdateProductDetail();
                    SPContext.Current.Item["Month"] = DateTime.Now.Month;
                    SPContext.Current.Item["Year"] = DateTime.Now.Year;
                }

                SPContext.Current.Web.AllowUnsafeUpdates = true;
                SaveButton.SaveItem(SPContext.Current, false, string.Empty);
                this.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
            }
        }

        protected void btApprove_Click(object o, EventArgs e)
        {
            if (CheckProduct())
            {
                SPContext.Current.Item["Status"] = "Approved";
                SPContext.Current.Item["Director"] = SPContext.Current.Web.CurrentUser;
                SPContext.Current.Item["Approved Date"] = DateTime.Now;

                SaveButton.SaveItem(SPContext.Current, false, string.Empty);
                Common.Common.SendEmail(web, Common.Common.GetEmailAddressesFromName(getUser("Created By").LoginName), string.Empty, "[SIMS][Remove Invalid Product Request][Approved]" + item["Title"], this.BuildMailContent());
                this.UpdateProduct();
                this.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
            }
        }

        protected void btReject_Click(object o, EventArgs e)
        {
            SPContext.Current.Item["Status"] = "Rejected";
            SPContext.Current.Item["Director"] = SPContext.Current.Web.CurrentUser;
            SPContext.Current.Item["Approved Date"] = DateTime.Now;

            SaveButton.SaveItem(SPContext.Current, false, string.Empty);
            Common.Common.SendEmail(web, Common.Common.GetEmailAddressesFromName(getUser("Created By").LoginName), string.Empty, "[SIMS][Remove Invalid Product Request][Rejected]" + item["Title"], this.BuildMailContent());
            this.Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
        }

        protected SPUser getUser(string field)
        {
            string strUser = SPContext.Current.Item[field].ToString();
            string[] information = strUser.Split(';');
            SPUser user = SPContext.Current.Web.SiteUsers.GetByID(Convert.ToInt32(information[0]));
            return user;
        }

        private string BuildMailContent()
        {
            string content = string.Empty;
            string path = Request.Url.Authority + "/Lists/Product Tracking/DispForm.aspx?ID=" + SPContext.Current.Item["ID"].ToString();

            content += "<b>Title:</b>" + item["Title"] + "<br/>";
            content += "<b>Date:</b>" + item["Created"] + "<br/>";
            content += "<b>Requestor:</b>" + getUser("Created By").Name + "<br/>";
            content += "<b>Description:</b>" + item["Description"] + "<br/><hr/>";

            if (item["Status"].ToString() != "Director Review")
            {
                content += "<b>Director:</b>" + getUser("Director").Name + "<br/>";
                content += "<b>Date:</b>" + item["Approved Date"] + "<br/>";
                content += "<b>Comment:</b>" + item["Director Comment"] + "<br/>";
            }
            content += "<hr/>" + path;
            return content;
        }
    }
}
